﻿using OpenTK.Graphics.OpenGL4;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Core.Rendering.Buffer
{
    public class VertexArrayObject:IDisposable
    {
        private readonly int _id;
        public IndexBufferObject? IndexBufferObject { get; private set; }
        public VertexArrayObject(IndexBufferObject? ibo,params VertexBufferObject[] vbo) 
        {
            IndexBufferObject = ibo;
            _id = GL.GenVertexArray();
            GL.BindVertexArray(_id);
            foreach(var vertexBufferObject in vbo)
            {
                vertexBufferObject.Bind();
                int offset = 0;
                foreach(var element in vertexBufferObject.Layout.Elements)
                {
                    GL.VertexAttribPointer(element.Location,element.Count,VertexAttribPointerType.Float,element.IsNormalized,vertexBufferObject.Stride,offset);
                    GL.EnableVertexAttribArray(element.Location);
                    offset += element.Count * sizeof(float);
                }
            }
        }
        public void Bind()
        {
            GL.BindVertexArray(_id);
            IndexBufferObject?.Bind();
        }
        public static void UnBind()
        {
            GL.BindVertexArray(0);
        }
        private void ReleaseUnmanageResources()
        {
            GL.DeleteVertexArray(_id);
        }
        public void Dispose()
        {
            ReleaseUnmanageResources();
            GC.SuppressFinalize(this);
        }
        ~VertexArrayObject()
        {
            ReleaseUnmanageResources();
        }
    }
}
